package cc.ufinity.networkdiagnose.widget;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.adapter.TestTaskListAdapter2;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.ChinaNetAccount;
import cc.ufinity.networkdiagnose.manager.ChinaNetAuthManager;
import cc.ufinity.networkdiagnose.manager.ChinaUnicomAccount;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.UnicomWebAuthManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class Test_Task_Widget_Other2 extends GeneralTestWidget {
	public final static String PREFS_NAME = "mymobile";
    public final static String PREFS_KEY = "number";
	
    private Thread thread;
	public static Activity ctx;
	private static String TAG = "TaskWidget";
	private ListView taskListView;
	private List<Task> tasks = null;
	private TelManager tm;
	private Handler handler;
	private String myPhoneNumber;
	private List<Map<String, Object>> datas;
	private TestTaskListAdapter2 tAdapter = null;
	private ImageView image1 = null, image2 = null;
	private ProgressBar pb1 = null, pb2 = null;
	private Button begin_test = null;
	private TextView tv_progress1 = null, tv_progress2 = null;
	private LinearLayout linearlayout = null; 
	private int testNum;
	private Button resultButton;
	private TextView titleView;
	private Task task; 
    private WlanManager wlanManager; 
	private boolean btnClick = false;
    private Map<String, String> map;
    private String address;
    private ChinaNetAuthManager chinaNet;
    private UnicomWebAuthManager unicomAuthManager;
    private boolean isWebAuthsucceed = false; 
	
    public boolean isTesting = true;
	
	public Test_Task_Widget_Other2(Activity context) {
		super(context);
		this.ctx = context;
		
		GlobalApp.test_Task_Widget_Other2 = this;
		GlobalApp.nowNetType = 1;
		GlobalApp.clearAll();
		
		wlanManager = new WlanManager(ctx);
		//task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);//获取任务
		if(GlobalApp.taskOtherList.size() == 0) {
			task = GlobalApp.taskOther;
		} else {
			task = GlobalApp.taskOtherList.get(GlobalApp.index);
		}
		
		
		if(task == null) {
			System.out.println("task传值失败" );
		}else {
			System.out.println("网络类型：" + task.selNetType);//  +task.scanResult.BSSID
		}
		
		inflate(context, R.layout.task_test_widget_wlan2, this);
		linearlayout = (LinearLayout)this.findViewById(R.id.progress_linearlayout_wlan2);
		image1 = new ImageView(ctx);
		image1.setBackgroundResource(R.drawable.test_before);
		image2 = new ImageView(ctx);
		image2.setBackgroundResource(R.drawable.test_after);
		linearlayout.addView(image1, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		pb2 = (ProgressBar)findViewById(R.id.progress2_wlan2);
		tv_progress1 = (TextView)findViewById(R.id.tv_progress1_wlan2);
		tv_progress2 = (TextView)findViewById(R.id.tv_progress2_wlan2);
		titleView = (TextView)findViewById(R.id.task_test_title_wlan2);
		
		if(task.scanResult.SSID.equals(WlanManager.SSID_ChinaNet)) {
			titleView.setText("电信WLAN测试");
		} else if(task.scanResult.SSID.equals(WlanManager.SSID_ChinaUnicom1)
				|| task.scanResult.SSID.equals(WlanManager.SSID_ChinaUnicom2)){
			titleView.setText("联通WLAN测试");
		} else {
			titleView.setText("WLAN测试");
		}
		
		begin_test = (Button)findViewById(R.id.begin_tesk_wlan2);
		begin_test.setText("测试中...");
		begin_test.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (btnClick) {
					ctx.setContentView(new TaskResult(ctx));
					btnClick = false;
				} 
			}
		});
		taskListView = (ListView) this.findViewById(R.id.taskTestListView_wlan2);
		taskListView.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Map<String, Object> r = (Map<String, Object>) taskListView
						.getAdapter().getItem(position);
				
				Log.d("结果查看", "详细信息: " + r.toString());
			}
		});
		
		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.TASK_LIST_LOADED_SUCCESS:
					init();
					dismissMessageDialog();
					break;
				case MessageWhat.TASK_LIST_LOADED_FAILED:
					dismissMessageDialog();
					showMessage(ctx, "获取任务列表失败.");
					break;
				case 2:
					showMessage(ctx, "本机手机号码无法获取.");
					dismissMessageDialog();
					break;
				case MessageWhat.WIFI_SUCESS_CONNECTED: 
					task.acIp = wlanManager.getIpAddress();
					ctx.getIntent().putExtra(TAG_REFER_TASK, task); 

					webAuth();
                    break;
				case MessageWhat.LOGIN_SUCCESS:  
				case MessageWhat.LOGIN_FAILED: 
					dismissMessageDialog();
					start();
					break;
				}
			}
		};

		chinaNet = GlobalApp.chinaNetAuthManager;
		if(chinaNet == null) {
			chinaNet = new ChinaNetAuthManager(ctx);
		}
		unicomAuthManager = GlobalApp.unicomAuthManager;
		if(unicomAuthManager == null) {
			unicomAuthManager = new UnicomWebAuthManager();
		}
		chinaNet.setHandler(handler);        //-----------------------
        wlanManager.setHandler(handler);
		tm = new TelManager(ctx);
		tm.setHandler(handler);  
		if(task!=null && task.scanResult!=null){
			DBManager db = new DBManager(ctx);
			if(task.scanResult.SSID.equals(WlanManager.SSID_ChinaNet)) {
				ChinaNetAccount Account = db.getChinaNetAccount();
				if((Account == null ||Account.userName == null || Account.password == null || Account.address == null)
						|| (Account.userName.equals("") || Account.password.equals("") || Account.address.equals(""))){
					inputChinaUserPassDialog(1);
				} else {
					connectNetWork();
				}
			} else if(task.scanResult.SSID.equals(WlanManager.SSID_ChinaUnicom1) 
					|| task.scanResult.SSID.equals(WlanManager.SSID_ChinaUnicom2)) {
				ChinaUnicomAccount Account = db.getUnicomAccount();
				if((Account == null ||Account.userName == null || Account.password == null || Account.address == null)
						|| (Account.userName.equals("") || Account.password.equals("") || Account.address.equals(""))){
					inputChinaUserPassDialog(2);
				} else {
					connectNetWork();
				}
			}else{
				connectNetWork();
			}
			db.release();
		} else {
		    connectNetWork();
		}
	}
	
	
	 private void connectNetWork(){

		   showMessageDialog(ctx, "正在连接网络..."); 
		   
		   thread = new Thread() { 
		        @Override
		        public void run() {
		        	wlanManager.setMobileDataEnabled(false);
               	 	wlanManager.openWifi();
	                wlanManager.connect(task.scanResult);
		        }  
		    };
	    	thread.start();
		   
	    }

	 Handler handlerChildMessage = new Handler() {

			@SuppressWarnings("unchecked")
			@Override
			public void handleMessage(Message messag) {
				if(isTesting) {
					Message msg = updateHandler.obtainMessage();
					Message message = new Message();
					Object tempObject;
					Map<String, Object> t2;
					if(datas!=null && datas.size()>0){
						switch(messag.arg1) {
						case MessageWhat.HANDLER_START:
							testNum = 0;
							System.out.println("= = = =  收到消息0   = = = =");
							msg.arg1 = testNum; 
						//	updateHandler.sendMessage(msg);
							tempObject =  taskListView.getAdapter().getItem(testNum);
							t2 = tempObject==null?null:(Map<String, Object>) tempObject;
							if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
								new HttpTestWidgetProxy(ctx, handlerChildMessage);
							} else {
								message.arg1 = MessageWhat.HANDLER_HTTP;
								GlobalApp.result_HTTP_test=new StringBuffer("\n\nHTTP测试项已跳过");
							}
							break;
						case MessageWhat.HANDLER_HTTP:
							System.out.println("= = = =  收到消息1   = = = =");
							msg.arg1 = testNum;
							testNum = testNum +1;
							updateHandler.sendMessage(msg);
							tempObject =  taskListView.getAdapter().getItem(testNum);
							t2 = tempObject==null?null:(Map<String, Object>) tempObject;
							if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
								new FtpTestProxyWidget(ctx, handlerChildMessage, tAdapter);
							} else {
								message.arg1 = MessageWhat.HANDLER_FTP;
								GlobalApp.result_FTP_test=new StringBuffer("\n\nFTP测试项已跳过");
							}
							break;
						case MessageWhat.HANDLER_FTP:
							System.out.println("= = = =  收到消息2   = = = =");
							msg.arg1 = testNum;
							testNum = testNum +1;
							updateHandler.sendMessage(msg);
							tempObject = taskListView.getAdapter().getItem(testNum);
							t2 = tempObject==null?null:(Map<String, Object>) tempObject;
							if(t2!=null && t2.get("taskSkip")!=null &&t2.get("taskSkip").equals("0")) { 
								new PingWidgetProxy(ctx, handlerChildMessage);
							} else   {
								message.arg1 = MessageWhat.HANDLER_PING;
								GlobalApp.result_PING_test=new StringBuffer("\n\nPING测试项已跳过");
							}   
							break;
						case MessageWhat.HANDLER_PING:
							System.out.println("= = = =  收到消息3   = = = =");
							msg.arg1 = testNum;
							testNum = testNum +1;
							updateHandler.sendMessage(msg);
							tempObject =  taskListView.getAdapter().getItem(testNum);
							t2 = tempObject==null?null:(Map<String, Object>) tempObject;
							if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")) {
								new ApRelevanceTestWidgetProxy(ctx, handlerChildMessage);
							} else {
								message.arg1 = MessageWhat.HANDLER_APREL;
								GlobalApp.result_AP_test=new StringBuffer("\n\nAP关联测试项已跳过");
							}
							break;
						case MessageWhat.HANDLER_APREL:
							System.out.println("= = = =  收到消息4   = = = =");
							msg.arg1 = testNum;
							testNum = testNum +1;
							updateHandler.sendMessage(msg);
							tempObject =  taskListView.getAdapter().getItem(testNum);
							t2 = tempObject==null?null:(Map<String, Object>) tempObject;
							if(t2!=null && t2.get("taskSkip")!=null && t2.get("taskSkip").equals("0")
									&&task.scanResult!=null && task.scanResult.SSID != null) {
								if(task.scanResult.SSID.equalsIgnoreCase(WlanManager.SSID_ChinaNet)) { 
									//电信WEB认证 
									new WebauthChinaTestWidgetProxy(ctx, handlerChildMessage);
								} else if(task.scanResult.SSID.equalsIgnoreCase(WlanManager.SSID_ChinaUnicom1) 
										|| task.scanResult.SSID.equalsIgnoreCase(WlanManager.SSID_ChinaUnicom2)) {
									//联通WEB认证 
									new WebauthUnicomTestWidgetProxy(ctx, handlerChildMessage);
								} else {
									message.arg1 = MessageWhat.HANDLER_WEB;
									GlobalApp.result_WEB_test=new StringBuffer("\n\nWeb认证测试条件不满足");
								}
							} else  {
								message.arg1 = MessageWhat.HANDLER_WEB;
								GlobalApp.result_WEB_test=new StringBuffer("\n\nWeb认证测试条件不满足");
							}
							break;
						case MessageWhat.HANDLER_WEB:
							System.out.println("= = = =  收到消息5   = = = =");
							msg.arg1 = testNum;
							testNum = testNum +1;
							updateHandler.sendMessage(msg);

							message.arg1 = MessageWhat.HANDLER_PEAP;
							GlobalApp.result_PEAP_test=new StringBuffer("\n\nPeap认证测试条件不满足");

							break;
						case MessageWhat.HANDLER_PEAP:
							System.out.println("= = = =  收到消息6   = = = =");
							msg.arg1 = testNum;
							testNum = testNum +1;
							updateHandler.sendMessage(msg);
							tempObject =  taskListView.getAdapter().getItem(testNum);
							t2 = tempObject==null?null:(Map<String, Object>) tempObject;
							if(t2!=null && t2.get("taskSkip")!=null &&t2.get("taskSkip").equals("0")) {
								new SegregateTestWidgetProxy(ctx, handlerChildMessage);
							} else if(t2.get("taskSkip").equals("1")) {
								message.arg1 = MessageWhat.HANDLER_SEGRE;
								GlobalApp.result_SEGREGATE_test =new StringBuffer("\n\n隔离测试项已跳过");
							}
							break;
						case MessageWhat.HANDLER_SEGRE:
							System.out.println("= = = =  收到消息7   = = = =");
							msg.arg1 = testNum;
							testNum = testNum +1;
							updateHandler.sendMessage(msg);
							tempObject =  taskListView.getAdapter().getItem(testNum);
							t2 = tempObject==null?null:(Map<String, Object>) tempObject;
							if(t2!=null && t2.get("taskSkip")!=null &&t2.get("taskSkip").equals("0")) {
								new RoamTestWidgetProxy(ctx, handlerChildMessage);
							} else  {
								message.arg1 = MessageWhat.HANDLER_ROAM;
								GlobalApp.result_ROAM_test =new StringBuffer("\n\n漫游测试项已跳过");
							}
							break;
						case MessageWhat.HANDLER_ROAM:
							System.out.println("= = = =  收到消息8   = = = =");
							msg.arg1 = testNum;
							testNum = testNum +1;
							updateHandler.sendMessage(msg);
							tempObject =  taskListView.getAdapter().getItem(testNum);
							t2 = tempObject==null?null:(Map<String, Object>) tempObject;
							if(t2!=null && t2.get("taskSkip")!=null &&t2.get("taskSkip").equals("0")) {
								new RssiTestWidgetProxy(ctx, handlerChildMessage);
							} else {
								message.arg1 = MessageWhat.HANDLER_RSSI;
								GlobalApp.result_SRRI_test =new StringBuffer("\n\n信号强度测试项已跳过");
							}
							break;
						case MessageWhat.HANDLER_RSSI:
							System.out.println("= = = =  收到消息9   = = = =");
							msg.arg1 = testNum;
							testNum = testNum +1;
							updateHandler.sendMessage(msg);
							isTesting = false;
//							btnClick = true;
//							begin_test.setText("查看结果");
							break;
						case MessageWhat.HANDLER_SNR:
							break;
						}
						handlerChildMessage.sendMessage(message);
					}
				}
			}
		};


	Thread updateThread = new Thread() {

		@Override
		public void run() {
			// TODO Auto-generated method stub 
			pb2.setMax(datas.size());
		}
		
	};
	Handler updateHandler = new Handler() {
		private String testingName = "";
		public void handleMessage(Message msg) {
			if(msg.arg1 == -1) {
				ProgressBar pb = new ProgressBar(ctx);
				pb.setVisibility(VISIBLE);
				linearlayout.removeAllViews();
				linearlayout.addView(pb, new LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
				@SuppressWarnings("unchecked")
				Map<String, Object> t = (Map<String, Object>) taskListView
					.getAdapter().getItem(msg.arg1+1);
				testingName = t == null ?"":(String)t.get("taskName");
				if(t!=null && t.get("taskSkip")!=null &&t.get("taskSkip").equals("0")) {
					t.put("taskState", "3");
				} else if(t!=null && t.get("taskSkip")!=null &&t.get("taskSkip").equals("1")) {
					System.out.println(testingName + " 已跳过");
				}
				
			} else if(msg.arg1 < datas.size()-1){
				@SuppressWarnings("unchecked")
				Map<String, Object> t1 = (Map<String, Object>) taskListView
					.getAdapter().getItem(msg.arg1);
				@SuppressWarnings("unchecked")
				Map<String, Object> t2 = (Map<String, Object>) taskListView
					.getAdapter().getItem(msg.arg1+1);
				testingName = t2==null?"":(String)t2.get("taskName");
				if(t1!=null && t1.get("taskSkip")!=null &&t1.get("taskSkip").equals("0")) {
					t1.put("taskState", "1");
				} else if(t1!=null && t1.get("taskSkip")!=null &&t1.get("taskSkip").equals("1")) {
					System.out.println(t1.get("taskName") + " 已跳过");
				}
				if(t2!=null && t2.get("taskSkip")!=null &&t2.get("taskSkip").equals("0")) {
					t2.put("taskState", "3");
				} else if(t2!=null && t2.get("taskSkip")!=null &&t2.get("taskSkip").equals("1")) {
					System.out.println(t2.get("taskName") + " 已跳过");
				}
			} else if(msg.arg1 == datas.size()-1) {
				@SuppressWarnings("unchecked")
				Map<String, Object> t = (Map<String, Object>) taskListView
					.getAdapter().getItem(msg.arg1);
				if(t!=null && t.get("taskSkip")!=null &&t.get("taskSkip").equals("0")) {
					t.put("taskState", "1");
				} else if(t!=null && t.get("taskSkip")!=null &&t.get("taskSkip").equals("1")) {
					System.out.println(t.get("taskName") + " 已跳过");
				}
			}
			
			if(msg.arg1+1 >= datas.size()) {
				tv_progress2.setText("检测完毕");
				btnClick = true;
				begin_test.setText("查看结果");
				linearlayout.removeAllViews();
				linearlayout.addView(image2, new LayoutParams(
						LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); 

				//=============================自动跳转到测试结果页面上传结果
				if (btnClick) {
					
					task.endsTime = StringUtils.getDateTime();
					
					if(GlobalApp.taskOtherList.size() == 0) {
						ctx.setContentView(new TaskResultWlan(ctx));
					} else {
						if(GlobalApp.index < GlobalApp.taskOtherList.size()-1) {
							GlobalApp.index ++;
							
							ctx.setContentView(new Test_Task_Widget_Other(ctx));
						} else {
							ctx.setContentView(new TaskResultAll(ctx));
						}
					}
					
					/*//showAlertDialog(ctx,"当前网络类型为GSM模式，进行TD测试请先切换至TD网络类型.");
					
					if(tm.getNetworkType()!=null && tm.getNetworkType().equals("EDGE")){
						
						showAlertDialog(ctx,"当前网络类型为GSM模式，进行TD测试请先切换至TD网络类型.");
					}else {
						ctx.setContentView(new Test_Task_Widget_TD(ctx)); //直接跳转到TD网络测试
					}*/
					
					
					btnClick = false;
				}
				ctx.getIntent().putExtra(TAG_REFER_TASK, task);
		    	//================================================================
			} else {
				tv_progress2.setText("正在检测第" + (msg.arg1+2) + "项：" + testingName);
			}
			
			tv_progress1.setText("总进度：" + 100*(msg.arg1+1)/datas.size() + "%");
			pb2.setProgress(msg.arg1+1);
			tAdapter.notifyDataSetChanged();  //更新Adapter
		}
	}; 
	
	private void webAuth(){
		isWebAuthsucceed = false;
		new Thread() {
			public void run() {
				if(wlanManager.getCurrentScanResult().SSID.equals(WlanManager.SSID_ChinaNet)) {
					if(chinaNet.canGotoWeb()) {
						return;
					} else {
						DBManager db = new DBManager(ctx);
				        ChinaNetAccount account = db.getChinaNetAccount();
				        db.release();
				        String  defaultUrl = ctx.getResources().getString(R.string.default_chinanet_url);
				        String username = "";
						String password = "";
						String address = "";
						if(account == null){
							isWebAuthsucceed = false;
							//  数据库错误
							showMessage(ctx, "WEB认证错误，请检查账号配置.");
						} else {
							username = account.userName;
							password = account.password;
							address = account.address;
							
							isWebAuthsucceed = chinaNetAuthManager.auth(defaultUrl, username, password, address);
						}
					}
					
				} else if(task.scanResult.SSID.equalsIgnoreCase(WlanManager.SSID_ChinaUnicom1) 
						|| task.scanResult.SSID.equalsIgnoreCase(WlanManager.SSID_ChinaUnicom2)) {
					if(unicomAuthManager.canGotoWeb()) {
						return;
					} else {
						DBManager db = new DBManager(ctx);
						ChinaUnicomAccount account = db.getUnicomAccount();
				        db.release();
				        String  defaultUrl = ctx.getResources().getString(R.string.default_chinanet_url);
				        String username = "";
						String password = "";
						String address = "";
						if(account == null){
							//  数据库错误
							showMessage(ctx, "WEB认证错误，请检查账号配置.");
						} else {
							username = account.userName;
							password = account.password;
							address = account.address;
							
							isWebAuthsucceed = unicomAuthManager.auth(defaultUrl, username, password, address);
						}
					}
				}
				
				if(isWebAuthsucceed) {
					wlanManager.sendMsg(MessageWhat.LOGIN_SUCCESS);
				} else {
					wlanManager.sendMsg(MessageWhat.LOGIN_FAILED);
				}
			}
		}.start();
		
	}
	
	private void webAuth2() {
		
		new Thread() {

			@Override
			public void run() {
				String url = "http://www.baidu.com";
				String userName = "18919665515";
				String pwd = "671970";
				String prov = "ah";
				
				chinaNet.auth(url, userName, pwd, prov);
			}
			
		}.start();
		
		
		
	}
	
	private void webLogout() {
		new Thread() {

			@Override
			public void run() {
				chinaNet.logout();
			}
			
		}.start();
	}
	
	
	public void start() {

		if (NetworkManager.detectNetworkConnectivity(ctx) == -1) {
			showMessage(ctx, "无法连接至因特网.");
			return;
		}
		myPhoneNumber = tm.getPhoneNumber();
		if (StringUtils.isEmpty(myPhoneNumber)) {
			showMessage(ctx, "获取本机号码失败,请输入.");
			showInputDialog();
			return;
		} else {
			loadTaskList();
		}
	}

	private void showInputDialog() {
		LayoutInflater factory = LayoutInflater.from(ctx);
		final View dialogView = factory.inflate(
				R.layout.input_phone_num_dialog, null);
		final EditText inputText = (EditText) dialogView
				.findViewById(R.id.phoneNumEditText);
		AlertDialog.Builder inputBuilder = new AlertDialog.Builder(ctx);
		inputBuilder.setTitle("提示");
	//	inputBuilder.setIcon(R.drawable.smile);
		inputBuilder.setView(dialogView);
		inputBuilder.setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (StringUtils.isEmpty(inputText.getText().toString())) {
							try {
								Field field = dialog.getClass().getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								field.set(dialog, false);
							} catch (Exception e) {
								e.printStackTrace();
							}
							showMessage(ctx, "请输入本机号码");
						} else {
							try {
								Field field = dialog.getClass().getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								field.set(dialog, true);
							} catch (Exception e) {
								e.printStackTrace();
							}
							myPhoneNumber = inputText.getText().toString();
							SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME,0);
				            SharedPreferences.Editor editor = settings.edit();
				            editor.putString(PREFS_KEY, myPhoneNumber);
				            editor.commit();   //保存手机号码
				            
							dialog.cancel();
							loadTaskList();
						}
					}
				});
		inputBuilder.setNegativeButton("取消", 
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				try {
					Field field = dialog.getClass().getSuperclass()
							.getDeclaredField("mShowing");
					field.setAccessible(true);
					field.set(dialog, true);
				} catch (Exception e) {
					e.printStackTrace();
				}
				dialog.cancel();
			}
		});
		Dialog dialog = inputBuilder.create();
		dialog.show();
	}

	private void loadTaskList() {
		//this.showMessageDialog(ctx, "正在加载任务列表...");
		new Thread() {
			public void run() {
				getTasks();
			}
		}.start();
	}

	private void init() { 
		tAdapter = new TestTaskListAdapter2(ctx, datas);
		taskListView.setAdapter(tAdapter);
		task.startTime = StringUtils.getDateTime();
		task.startsTime = StringUtils.getDateTime();
		testNum = 0; 
		pb2.setMax(datas.size());
		Message msg = new Message();
		msg.arg1 = -1;
		updateHandler.sendMessage(msg);

		Message message = handlerChildMessage.obtainMessage();
		message.arg1 = MessageWhat.HANDLER_START;
		message.sendToTarget();
	}
	
	private List<Map<String, Object>> getTasks() {
		List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();

		try {
			tasks = new ArrayList<Task>();
			Task tk0 = new Task();  Task tk1 = new Task();
			Task tk2 = new Task();  Task tk3 = new Task();
			Task tk4 = new Task();  Task tk5 = new Task();
			Task tk6 = new Task();  Task tk7 = new Task();
			Task tk8 = new Task();  Task tk9 = new Task();
			Task tk = new Task();
			tk0.taskName = "HTTP测试";  tk1.taskName = "FTP测试";
			tk2.taskName = "PING测试";  tk3.taskName = "AP关联";
			tk4.taskName = "WEB认证";  tk5.taskName = "PEAP认证";
//			tk6.taskName = "SIM认证";  
			tk7.taskName = "隔离测试";
			tk8.taskName = "漫游测试";  
//			tk9.taskName = "信噪比测试";
			tk.taskName = "信号强度RSSI"; 

				tasks.add(tk0);  tasks.add(tk1);
				tasks.add(tk2);  tasks.add(tk3);
				tasks.add(tk4);  tasks.add(tk5);
				tasks.add(tk7);  
				tasks.add(tk8); 
				tasks.add(tk);

			Map<String, Object> t = null;
			for (Task task : tasks) {
				t = new HashMap<String, Object>();
				t.put("taskName", task.taskName);
				t.put("taskState", "0");  //检测状态
				t.put("taskSkip", "0");   //是否跳过
				
				res.add(t);
			}
			datas = res;
			Message e = new Message();
			e.what = MessageWhat.TASK_LIST_LOADED_SUCCESS;
			handler.sendMessage(e);

		} catch (Exception e) {
			Log.e(TAG, "解析XML任务时出错：", e);
			Message e1 = new Message();
			e1.what = MessageWhat.TASK_LIST_LOADED_FAILED;
			handler.sendMessage(e1);
		}
		return res;
	}
	public void showAlertDialog(final Activity ctx,final String message) { 
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx); 
    	builder.setTitle("测试提示");   
    	builder.setMessage(message); 
    	builder.setCancelable(false);
 		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
 			public void onClick(DialogInterface dialog, int id) { 
 				try {
 					ctx.getIntent().putExtra(MessageWhat.INDEX_Test_Task_Widget_Wlan_WIDGET, 1);
 					
// 					ctx.startActivity(new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS));
 					//ctx.startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));
 					//ctx.startActivity(new Intent(Settings.ACTION_SETTINGS));
 					Intent intent = new Intent(Intent.ACTION_MAIN);
 					intent.setClassName("com.android.phone", "com.android.phone.NetworkSetting");
 					ctx.startActivity(intent);
 					GlobalApp.isWlanTO_TD_GSM = true;
 				} catch (Exception e) {
 					showAlertDialog(ctx, message);
 					showMessage(ctx, "该手机不支持TD/GSM网络切换");
 				}
 			}
 		}); 
 		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
 			public void onClick(DialogInterface dialog, int id) { 
 				ctx.setContentView(new Test_Task_Widget_GSM(ctx)); //直接跳转到GSM网络测试
        		dialog.cancel();
 			}
 		});
 		wifiListDialog = builder.create();
        wifiListDialog.show();
    }
	
	 /**
	    * 中国电信配置认证账号和无线密码
	    * @param ctx
	    * @param wlanManager
	    * @param handler
	    */
	   public  void inputChinaUserPassDialog(final int flag) {
		   	final String [] countriesStr1 = {
		   		"安徽","北京","全国中心","天津","河北","山西", "内蒙古","辽宁", "吉林", "黑龙江","湖北", "湖南", "河南",
		   		 "江苏","山东","上海","浙江", "福建","江西", "广东","海南","广西", "四川","重庆","贵州","云南","西藏","陕西",
		   		 "甘肃","青海","宁夏", "新疆","澳门", "全国", "统一账号"
		   		};
		   	final String [] countriesStr2 = {
				"安徽","北京","天津","河北","山西", "内蒙古","辽宁", "吉林", "黑龙江","湖北", "湖南", "河南",
				 "江苏","山东","上海","浙江", "福建","江西", "广东","海南","广西", "四川","重庆","贵州","云南","西藏","陕西",
				 "甘肃","青海","宁夏", "新疆"
				};
		   	init1(flag);
		   	LayoutInflater factory = LayoutInflater.from(ctx);
		   	ArrayAdapter<String> adapter1;
		   	
		   	final View dialogView;
		   	final EditText identText; 
			final EditText passText; 
			final Spinner spinner;
		   	if(flag == 1) {
		   		adapter1 = new ArrayAdapter<String>(ctx,android.R.layout.simple_spinner_dropdown_item,
		   			countriesStr1);
		   		dialogView = factory.inflate(R.layout.web_input_user_pass_dialog_chinanet, null);
		   		identText = (EditText) dialogView.findViewById(R.id.webusername_chinanet); 
				passText = (EditText) dialogView.findViewById(R.id.webpassword_chinanet); 
				spinner=(Spinner)dialogView.findViewById(R.id.mySpinner_chinanet);
		   	} else {
		   		adapter1 = new ArrayAdapter<String>(ctx,android.R.layout.simple_spinner_dropdown_item,
		   	   			countriesStr2);
		   		dialogView = factory.inflate(R.layout.web_input_user_pass_dialog_chinaunicom, null);
		   		identText = (EditText) dialogView.findViewById(R.id.webusername_chinaunicom); 
				passText = (EditText) dialogView.findViewById(R.id.webpassword_chinaunicom); 
				spinner=(Spinner)dialogView.findViewById(R.id.mySpinner_chinaunicom);
		   	}
			
			
			spinner.setAdapter(adapter1);
			address=map.get("安徽").toString();
			spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
				public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
					System.out.println("+++++++++++"+spinner.getSelectedItem().toString());
					 address=map.get(spinner.getSelectedItem().toString());
				}
				public void onNothingSelected(AdapterView<?> arg0) {
					
				}});
			/*String str=spinner.get*/
	       AlertDialog.Builder builder = new AlertDialog.Builder(ctx); 
	       if(flag == 1) {
	    	   builder.setTitle("中国电信WEB认证账号"); 
	       } else {
	    	   builder.setTitle("中国联通WEB认证账号"); 
	       }
	       
	       builder.setView(dialogView); 
	       builder.setCancelable(false); 
	       builder.setPositiveButton("认证", new DialogInterface.OnClickListener() {
	        	public void onClick(DialogInterface dialog, int id) {
	        		String username = identText.getText().toString(); 
	        		String password = passText.getText().toString();
		    		 
		    		 try { 
		    			 Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
						 field.setAccessible(true);
		    			 if (StringUtils.isEmpty(username)) {
							field.set(dialog, false);
							showMessage(ctx, "请输入认证账号");
						 }else if (StringUtils.isEmpty(password)) {
							field.set(dialog, false);
			    			showMessage(ctx, "请输入无线密码");
						 }else{ 
							 field.set(dialog, true);  
							 DBManager db = new DBManager(ctx);
							 
							 if(flag == 1) {
								 ChinaNetAccount account = new ChinaNetAccount();
								 account.userName = username;
								 account.password = password;
								 account.address = address;
								 db.saveChinaNetAccount(account);
							 } else {
								 ChinaUnicomAccount account = new ChinaUnicomAccount();
								 account.userName = username;
								 account.password = password;
								 account.address = address;
								 db.saveUnicomAccount(account);
							 }
							 
							 
							 db.release();
						 }
		    		 } catch (Exception e) {
							e.printStackTrace();
							showMessage(ctx, "配置失败，请稍后重试");
					 }
		    		 connectNetWork();
	       	}
	       });
	       builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
	       	public void onClick(DialogInterface dialog, int id) {
	       		try {
						Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
						field.setAccessible(true);
						field.set(dialog, true);
					} catch (Exception e) {
						e.printStackTrace();
					}
	 //      		mSendBroadcast(ctx); 
	       		dialog.cancel();
	       		connectNetWork();
	       	}
	       });
		 	wifiListDialog = builder.create();
		    wifiListDialog.show(); 

	   }

	   public void init1(int flag){
	   	map = new HashMap<String, String>();
	   	if(flag == 1) {
	   		map.put("全国中心","zx" );
	        map.put("北京", "bj" );
	        map.put("天津", "tj" );
	        map.put("河北", "he" );
	        map.put("山西", "sx");
	        map.put("内蒙古", "nm");
	        map.put("辽宁", "ln" );
	        map.put("吉林", "jl");
	        map.put("黑龙江", "hl");
	        map.put("湖北", "hb");
	        map.put("湖南", "hn");
	        map.put("河南", "ha");
	        map.put("江苏", "js");
	        map.put("山东", "sd");
	        map.put("安徽", "ah");
	        map.put("上海", "sh");
	        map.put("浙江", "zj");
	        map.put("福建", "fj");
	        map.put("江西", "jx");
	        map.put("广东", "gd");
	        map.put("海南", "hi");
	        map.put("广西", "gx");
	        map.put("四川", "sc");
	        map.put("重庆", "cq");
	        map.put("贵州", "gz");
	        map.put("云南", "yn");
	        map.put("西藏", "xz");
	        map.put("陕西", "sn");
	        map.put("甘肃", "gs");
	        map.put("青海", "gh");
	        map.put("宁夏", "nx");
	        map.put("新疆", "xj");
	        map.put("澳门", "am");
	        map.put("全国", "qg");
	        map.put("统一账号", "udb");
	   	} else {
	   		map.put("安徽", "@wlan.ah.chinaunicom.cn");
	   		map.put("北京", "@wlan.bj.chinaunicom.cn" );
	   	    map.put("天津", "@wlan.tj.chinaunicom.cn" );
	   	    map.put("河北", "@wlan.he.chinaunicom.cn" );
	   	    map.put("山西", "@wlan.sx.chinaunicom.cn");
	   	    map.put("内蒙古", "@wlan.nm.chinaunicom.cn");
	   	    map.put("辽宁", "@wlan.ln.chinaunicom.cn" );
	   	    map.put("吉林", "@wlan.jl.chinaunicom.cn");
	   	    map.put("黑龙江", "@wlan.hl.chinaunicom.cn");
	   	    map.put("湖北", "@wlan.hb.chinaunicom.cn");
	   	    map.put("湖南", "@wlan.hn.chinaunicom.cn");
	   	    map.put("河南", "@wlan.ha.chinaunicom.cn");
	   	    map.put("江苏", "@wlan.js.chinaunicom.cn");
	   	    map.put("山东", "@wlan.sd.chinaunicom.cn");
	   	    map.put("上海", "@wlan.sh.chinaunicom.cn");
	   	    map.put("浙江", "@wlan.zj.chinaunicom.cn");
	   	    map.put("福建", "@wlan.fj.chinaunicom.cn");
	   	    map.put("江西", "@wlan.jx.chinaunicom.cn");
	   	    map.put("广东", "@wlan.gd.chinaunicom.cn");
	   	    map.put("海南", "@wlan.hi.chinaunicom.cn");
	   	    map.put("广西", "@wlan.gx.chinaunicom.cn");
	   	    map.put("四川", "@wlan.sc.chinaunicom.cn");
	   	    map.put("重庆", "@wlan.cq.chinaunicom.cn");
	   	    map.put("贵州", "@wlan.gz.chinaunicom.cn");
	   	    map.put("云南", "@wlan.yn.chinaunicom.cn");
	   	    map.put("西藏", "@wlan.xz.chinaunicom.cn");
	   	    map.put("陕西", "@wlan.sn.chinaunicom.cn");
	   	    map.put("甘肃", "@wlan.gs.chinaunicom.cn");
	   	    map.put("青海", "@wlan.qh.chinaunicom.cn");
	   	    map.put("宁夏", "@wlan.nx.chinaunicom.cn");
	   	    map.put("新疆", "@wlan.xj.chinaunicom.cn");
	   	}
			
		}
}
